import asyncio
import os
import sys
import urllib.request
from http.client import HTTPResponse
from typing import Union

import motor
from motor.motor_asyncio import AsyncIOMotorDatabase

sys.path.append(os.path.dirname(os.path.dirname(
    os.path.abspath(__file__)))) if __name__ == '__main__' else None
from util.config import SETTINGS  # noqa
from util.serialization import json_str_to_dict  # noqa

client = motor.motor_asyncio.AsyncIOMotorClient(
    'mongodb://%s:%s@%s:%s/?authSource=%s' % (
        SETTINGS['mongodb']["username"],
        SETTINGS['mongodb']["password"],
        SETTINGS['mongodb']["host"],
        SETTINGS['mongodb']["port"],
        SETTINGS['mongodb']["authSource"]
    )

)
db: AsyncIOMotorDatabase = client.binance_public_data


def get_all_symbols(url) -> dict:
    """
    Get all symbols from a given url
    """
    url = "https://api.binance.com/api/v3/exchangeInfo"
    response: HTTPResponse = urllib.request.urlopen(url)
    data: bytes = response.read()
    text: str = data.decode("utf-8")

    return json_str_to_dict(text)


async def do_insert(collection: str, data: Union[dict, list]):
    """插入数据"""
    if isinstance(data, dict):
        result = await db[collection].insert_one(data)
    elif isinstance(data, list):
        result = await db[collection].insert_many(data)

    return result.inserted_ids


async def insert_all_symbols(collection: str, query: dict) -> None:
    """insert all symbols"""
    result = await db[collection].find_one(query)
    await do_insert('symbols', result['symbols'])


async def find_one(collection: str, query: dict):
    """find one document"""
    result = await db[collection].find_one(query)
    return result


async def do_count(collection: str) -> int:
    """count documents"""
    result = await db[collection].count_documents({})
    return result


if __name__ == '__main__':
    asyncio.get_event_loop().run_until_complete(
        # find_one('symbols', {'symbol': 'ETHUSDT'})
        do_count('symbols')
    )
